package java_thinking.unit_21.Exercise.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/8/7 19:04
 */

public class ThreadlocalTest {
    static ThreadLocal<String> localVariable = new ThreadLocal<>();
    static AtomicBoolean aBoolean = new AtomicBoolean(false);
    static AtomicBoolean aBoolean1 = new AtomicBoolean(false);
    static AtomicInteger integer = new AtomicInteger(1);
    static ExecutorService pool = Executors.newCachedThreadPool();
    public static void main(String[] args) {
        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    localVariable.set("threadOne local variable");

                    System.out.println("threadOne set localVariable = "+ localVariable.get());
                    integer.incrementAndGet();
                } while (integer.get() < 2);
                do {
                    print("threadOne");

                    System.out.println("threadOne remove after" + ":" + localVariable.get());
                    integer.incrementAndGet();
                } while (2 < integer.get() && integer.get() <=3);
            }
        });

        Thread threadTwo = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                do {
                    localVariable.set("threadTwo local variable");
                    System.out.println("threadTwo set localVariable = "+ localVariable.get());
                    integer.incrementAndGet();
                } while (1 < integer.get() && integer.get() <=2);
                do {
                    print("threadTwo");
                    System.out.println("threadTwo remove after" + ":" + localVariable.get());
                    integer.incrementAndGet();
                } while (3 < integer.get() && integer.get() <=4);
            }
        });
        threadOne.start();
        threadTwo.start();


    }
    static void print(String str) {
        System.out.println(str + ":" + localVariable.get());
        if (str.equals("threadOne")) {
            //Thread1先对 localVariable 操作，但是 Thread1 对 localVariable 仍然能读取到
            localVariable.remove();
        }
    }

}
